package com.ay.weixin.fdc.boss.project.event;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.controller.loader.FilePostForm;
import org.lizar.ioc.Container;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.boss.autoreply.event.ReplySetting;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectDao;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectGrahDao;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectGrahImgDao;
import com.ay.weixin.fdc.boss.project.domain.FDCProject;
import com.ay.weixin.fdc.boss.project.domain.FDCProjectGrah;
import com.ay.weixin.fdc.boss.project.domain.FDCProjectGrahImg;

public class ProjectGrahMC extends Event {

	private IbatisProjectGrahDao grah_dao;
	
	private IbatisProjectDao project_dao;
	
	private IbatisProjectGrahImgDao img_dao;
	
	@Override
	public void init_property() throws Exception {
		grah_dao=Container.get(IbatisProjectGrahDao.class);
		project_dao=Container.get(IbatisProjectDao.class);
		img_dao=Container.get(IbatisProjectGrahImgDao.class);
	}

	@Override
	public String default_handling_path() {
		return "/mc/fdc/project/grah/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		Customer adm=(Customer)el.getSessionAttr("customer");
		if(adm==null){
			el.response_to_root(CustomerLogin.login_path());
		}else{
			try{	
				if(StringHelper.equals(el.queryPath(4), "")){
					index(el);
				}else if(StringHelper.equals(el.queryPath(4), "add_prepare")){
					add_prepare(el);
				}else if(StringHelper.equals(el.queryPath(4), "detail")){
					detail(el);
				}else if(StringHelper.equals(el.queryPath(4), "add")){
					add(el);
				}else if(StringHelper.equals(el.queryPath(4), "delete")){
					delete(el);
				}else if(StringHelper.equals(el.queryPath(4), "update")){
					update(el);
				}else if(StringHelper.equals(el.queryPath(4), "img_add")){
					img_add(el,adm.getWxprojectID());
				}else if(StringHelper.equals(el.queryPath(4), "img_delete")){
					img_delete(el);
				}else if(StringHelper.equals(el.queryPath(4), "img_update")){
					img_update(el,adm.getWxprojectID());
				}
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg",el.i18("fdc.project.db.failure"));
				index(el);
			}
			
		}
	}
	
	private void img_delete(EventLoader el) throws SQLException, IOException, ServletException{
		long img_id=el.getLong("img_id");
		String msg=null;
		
		FDCProjectGrahImg img=img_dao.get(img_id);
		if(img==null){
			msg=el.i18("fdc.project.grah.not.exists");
			el.setAttr("msg",msg);
			detail(el);
			return;
		}
		
		el.setAttr("id",img.getGrah_id());
		
		img_dao.delete(img_id);
		
		File f=new File(el.getRealPath(img.getUrl()));
		f.delete();
		
		if(msg==null){
			msg=el.i18("fdc.project.grah.delete.success");
		}
		el.setAttr("msg",msg);
		
		detail(el);
	}
	
	private void img_update(EventLoader el,long wxproject_id) throws SQLException, IOException, ServletException{
		
		FilePostForm post_form=el.parseFilePostForm(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);
		String msg=null;
		if(post_form.getErrorMsg()!=null){
       	 msg=el.i18("fdc.project.grah.img.update.failed")+","+post_form.getErrorMsg();
       	 el.setAttr("msg", msg);
       	 index(el);
         return;
       }
	   long id=post_form.getLong("id",-1);
	   if(id==-1){
			el.response_to_root("/mc/fdc/project");
			return;
		}
	   FDCProjectGrahImg img=img_dao.get(id);
	   if(img==null){
		   el.setAttr("msg",el.i18("fdc.project.grah.not.exists"));
		   el.setAttr("id",post_form.getLong("grah_id"));
		   detail(el);
		   return;
	   }
	   el.setAttr("id",img.getGrah_id());
	   String info=post_form.getStr("info");
	   int pos=post_form.getInt("pos");
	   String url=img.getUrl();
       FileItem pic=post_form.getFileItem(0);
       File savedFile=null;
       if(pic!=null&&pic.getName().toLowerCase().endsWith(".jpg")){
    	   String file_name=UUID.randomUUID().toString()+".jpg";
           String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
           savedFile=new File(file_path);
           if(!savedFile.getParentFile().exists()){
             	 savedFile.getParentFile().mkdirs();
           }
           try {
				pic.write(savedFile);
			} catch (Exception e) {
				e.printStackTrace();
				msg=el.i18("fdc.project.image.save.failed");
				el.setAttr("msg",msg);
				detail(el);
				return;
			}
    	   url=ReplySetting.getRelatImagePath(el,wxproject_id, file_name);
       }
		
		img.setId(id);
		img.setInfo(info);
		img.setPos(pos);
		img.setUrl(url);
		
		 try{
			 img_dao.update(img);
		 }catch(SQLException e){
			 e.printStackTrace();
			 msg=el.i18("fdc.project.db.failure");
			 if(savedFile!=null)savedFile.delete();
		 }
		if(msg==null){
			msg=el.i18("fdc.project.img.update.success");
		}
		el.setAttr("msg",msg);
		
		detail(el);
		
	}	
	
	private void img_add(EventLoader el,long wxproject_id) throws SQLException, IOException, ServletException{
		
		FilePostForm post_form=el.parseFilePostForm(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);
		String msg=null;
		if(post_form.getErrorMsg()!=null){
       	 msg=el.i18("fdc.project.update.failed")+","+post_form.getErrorMsg();
       	 el.setAttr("msg", msg);
       	 index(el);
         return;
       }
		long id=post_form.getLong("id",-1);
	       String info=post_form.getStr("info");
		
			if(id==-1){
				el.response_to_root("/mc/fdc/project");
				return;
			}
       FileItem pic=post_form.getFileItem(0);
       if(pic==null){
      	 msg=el.i18("fdc.project.image.upload.nofile.found");
      	 el.setAttr("msg",msg);
      	 el.setAttr("id", id);
     	  	 detail(el);
           return;
      }
      if(!pic.getName().toLowerCase().endsWith(".jpg")){
      	 msg=el.i18("fdc.project.image.postfix.notsupport");
      	 el.setAttr("msg",msg);
      	 el.setAttr("id", id);
      	detail(el);
           return;
      }
      
       String file_name=UUID.randomUUID().toString()+".jpg";
       String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
       File savedFile=new File(file_path);
       if(!savedFile.getParentFile().exists()){
         	 savedFile.getParentFile().mkdirs();
       }
      
       
		
		
		el.setAttr("info",info);
		el.setAttr("id",id);
		FDCProjectGrahImg img=new FDCProjectGrahImg();
		img.setGrah_id(id);
		img.setInfo(info);
		img.setPos(img_dao.getMaxPos(id));
		img.setUrl(ReplySetting.getRelatImagePath(el,wxproject_id, file_name));
		

		 try {
				pic.write(savedFile);
			} catch (Exception e) {
				e.printStackTrace();
				msg=el.i18("fdc.project.image.save.failed");
				el.setAttr("msg",msg);
				detail(el);
				return;
		}
		 
		
		 try{
			 img_dao.insert(img);
		 }catch(SQLException e){
			 e.printStackTrace();
			 msg=el.i18("fdc.project.db.failure");
			 savedFile.delete();
		 }
		if(msg==null){
			msg=el.i18("fdc.project.img.add.success");
		}
		el.setAttr("msg",msg);
		el.removeAttr("info");
		
		detail(el);
		
	}	
	
	
	private void update(EventLoader el) throws IOException, ServletException, SQLException{
		
		long id=el.getLong("id",-1);
		
		String name=el.getStr("name");
		
		String sub_name=el.getStr("sub_name");
		
		String detail=el.getStr("detail");
		
		String room=el.getStr("room");
		
		int pos=el.getInt("pos");
		
		String msg=null;
		if(id==-1){
			index(el);
			return;
		}
		FDCProjectGrah grah=grah_dao.get(id);
		if(grah==null){
			msg=el.i18("fdc.project.grah.not.exists");
			el.setAttr("msg",msg);
			index(el);
			return;
		}
		el.setAttr("project_id",grah.getProject_id());
		if(StringHelper.isNull(name)){
			msg=el.i18("fdc.project.grah.name.is.empty");
			el.setAttr("msg",msg);
			index(el);
			return;
		}
		
		grah.setDetail(detail);
		grah.setName(name);
		grah.setPos(pos);
		grah.setRoom(room);
		grah.setSub_name(sub_name);
		grah.setId(id);
		
		grah_dao.update(grah);
		
		if(msg==null){
			msg=el.i18("fdc.project.grah.update.success");
		}
		el.setAttr("msg",msg);
		
		index(el);
		
		
	}
	
	private void delete(EventLoader el) throws SQLException, IOException, ServletException{
		long id=el.getLong("id");
		String msg=null;
		FDCProjectGrah grah=grah_dao.get(id);
		msg=delete_from_grah(el,grah);
		if(StringHelper.isNotNull(msg)){
			el.setAttr("msg",msg);
			index(el);
			return;
		}
		el.setAttr("project_id",grah.getProject_id());
		
		if(msg==null){
			msg=el.i18("fdc.project.grah.delete.success");
		}
		el.setAttr("msg",msg);
		
		index(el);
	}
	
	public String delete_from_grah(EventLoader el,FDCProjectGrah grah) throws SQLException{
		
		if(grah==null){
			return el.i18("fdc.project.grah.not.exists");
		}
		List<FDCProjectGrahImg> list=img_dao.getProjectGrahImgs(grah.getId());
		img_dao.deleteByGrahId(grah.getId());
		if(list!=null&&!list.isEmpty()){
			for(FDCProjectGrahImg img:list){
				File f=new File(el.getRealPath(img.getUrl()));
				f.delete();
			}
		}
		grah_dao.delete(grah.getId());
		return null;
	}
	
	private void add(EventLoader el) throws IOException, ServletException, SQLException{
		
		String name=el.getStr("name");
		
		String sub_name=el.getStr("sub_name");
		
		String detail=el.getStr("detail");
		
		long project_id=el.getLong("project_id");
		
		String type=el.getStr("type");
		
		String room=el.getStr("room");
		String msg=null;
		if(!project_dao.exists(project_id)){
			msg=el.i18("fdc.project.not.exists");
			el.setAttr("msg",msg);
			index(el);
			return;
		}
		FDCProjectGrah grah=new FDCProjectGrah();
		
		grah.setDetail(detail);
		grah.setName(name);
		
		grah.setProject_id(project_id);
		grah.setRoom(room);
		grah.setSub_name(sub_name);
		grah.setType(type);
		
		el.setAttr("grah", grah);
		if(StringHelper.isNull(name)){
			msg=el.i18("fdc.project.grah.name.is.empty");
			el.setAttr("msg",msg);
			add_prepare(el);
			return;
		}
		
	
		grah.setPos(grah_dao.getMaxPos(project_id));
		
		grah_dao.insert(grah);
		
		if(msg==null){
			msg=el.i18("fdc.project.grah.add.success");
		}
		el.setAttr("msg",msg);
		
		index(el);
		
		
	}
	
	private void detail(EventLoader el) throws SQLException, IOException, ServletException{
		long id=el.getLong("id",-1);
		if(id==-1){
			id=el.getAttr("id", -1l);
		}
		if(id==-1){
			el.response_to_root("/mc/fdc/project");
			return;
		}
		FDCProjectGrah grah=null;
		
		grah=grah_dao.get(id);
		
		List<FDCProjectGrahImg> imglist=img_dao.getProjectGrahImgs(id);
		
		el.setAttr("imglist", imglist);
		el.setAttr("grah", grah);
		el.template("/WEB-INF/template/boss/fdc/project/grah/detail.vm");
	}
	
	private void add_prepare(EventLoader el) throws IOException, ServletException, SQLException{
		long project_id=el.getLong("project_id",-1);
		if(project_id==-1){
			project_id=el.getAttr("project_id", -1l);
		}
		if(project_id==-1){
			el.response_to_root("/mc/fdc/project");
			return;
		}
		
		FDCProject project=project_dao.get(project_id);
		el.setAttr("project", project);
		el.setAttr("project_id", project_id);
		el.template("/WEB-INF/template/boss/fdc/project/grah/add.vm");
	}
	
	private void index(EventLoader el) throws IOException, ServletException{
		long project_id=el.getLong("project_id",-1);
		if(project_id==-1){
			project_id=el.getAttr("project_id", -1l);
		}
		if(project_id==-1){
			el.response_to_root("/mc/fdc/project");
			return;
		}
		List<FDCProjectGrah> list=null;
		
		try {
			list=grah_dao.getProjectGrahs(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("fdc.project.db.failure"));
		}
		FDCProject project=null;
		try {
			project = project_dao.get(project_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("fdc.project.db.failure"));
		}
		el.setAttr("project", project);
		el.setAttr("project_id", project_id);
		el.setAttr("list", list);
		el.template("/WEB-INF/template/boss/fdc/project/grah/index.vm");
	}
	

}
